// src/main/ets/utils/RdbManager.ts
import relationalStore from '@ohos.data.relationalStore';
import common from '@ohos.app.ability.common'; // 添加 common 模块导入

const DB_NAME = 'userData.db';
const TABLE_NAME = 'users';
const SQL_CREATE_TABLE = `
  CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    useraccount TEXT NOT NULL UNIQUE,
    password TEXT NOT NULL
  )`;

export class RdbManager {
  private static rdbStore: relationalStore.RdbStore | null = null;

  // 修正：使用 common.Context 类型
  static async initRdbStore(context: common.Context) {
    const config: relationalStore.StoreConfig = {
      name: DB_NAME,
      securityLevel: relationalStore.SecurityLevel.S1
    };
    try {
      this.rdbStore = await relationalStore.getRdbStore(context, config);
      await this.rdbStore.executeSql(SQL_CREATE_TABLE);
      console.info('Database initialized');
    } catch (err) {
      console.error(`Failed to init RdbStore. Code:${err.code},message:${err.message}`);
    }
  }

  // 用户注册
  static async registerUser(useraccount: string, password: string): Promise<boolean> {
    if (!this.rdbStore) return false;

    const valueBucket: relationalStore.ValuesBucket = {
      'useraccount': useraccount,
      'password': password
    };

    try {
      await this.rdbStore.insert(TABLE_NAME, valueBucket);
      return true;
    } catch (err) {
      console.error(`Registration failed. Code:${err.code},message:${err.message}`);
      return false;
    }
  }

  // 用户登录验证
  static async loginUser(useraccount: string, password: string): Promise<boolean> {
    if (!this.rdbStore) return false;

    const predicates = new relationalStore.RdbPredicates(TABLE_NAME);
    predicates.equalTo('useraccount', useraccount)
      .and()
      .equalTo('password', password);

    try {
      const result = await this.rdbStore.query(predicates, ['id']);
      return result.rowCount > 0;
    } catch (err) {
      console.error(`Login query failed. Code:${err.code},message:${err.message}`);
      return false;
    }
  }

  // 检查用户名是否存在
  static async checkUseraccountExists(useraccount: string): Promise<boolean> {
    if (!this.rdbStore) return false;

    const predicates = new relationalStore.RdbPredicates(TABLE_NAME);
    predicates.equalTo('useraccount', useraccount);

    try {
      const result = await this.rdbStore.query(predicates, ['id']);
      return result.rowCount > 0;
    } catch (err) {
      console.error(`Useraccount check failed. Code:${err.code},message:${err.message}`);
      return false;
    }
  }

  // 重置密码
  static async resetPassword(useraccount: string, newPassword: string): Promise<true | 'same' | false> {
    if (!this.rdbStore) return false;
    const predicates = new relationalStore.RdbPredicates(TABLE_NAME);
    predicates.equalTo('useraccount', useraccount);
    try {
      // 查询当前密码
      const result = await this.rdbStore.query(predicates, ['password']);
      if (result.rowCount > 0 && result.goToFirstRow()) {
        const oldPassword = result.getString(result.getColumnIndex('password'));
        if (oldPassword === newPassword) {
          return 'same'; // 新旧密码一致
        }
      }
      // 更新密码
      const valueBucket = { password: newPassword };
      const rows = await this.rdbStore.update(valueBucket, predicates);
      return rows > 0;
    } catch (err) {
      console.error(`Reset password failed. Code:${err.code},message:${err.message}`);
      return false;
    }
  }

  // 设置当前登录用户
  static setCurrentUser(useraccount: string) {
    AppStorage.setOrCreate('isLoggedIn', true);
    AppStorage.setOrCreate('currentUser', useraccount);
    console.info(`User ${useraccount} logged in successfully`);
  }

  // 获取当前登录用户
  static getCurrentUser(): string {
    return AppStorage.get('currentUser') || '';
  }

  // 检查是否已登录
  static isLoggedIn(): boolean {
    return AppStorage.get('isLoggedIn') || false;
  }

  // 清除当前登录用户数据
  static clearCurrentUser() {
    AppStorage.delete('isLoggedIn');
    AppStorage.delete('currentUser');
    console.info('User logged out successfully');
  }
}